/**
    Copyright (c) 2012 ATTi 
    All rights reserved.
    Author: Michael Shu
    Purpose : 1. AD-31013 : take "Customer ID" values, make comma delimted string. Insert string into field "AF Customer ID". 
    Date: 5/3/2012
*/

trigger CaseProductNatoUpdate on Case_Product__c (after insert, after update, after delete, after undelete) {
	Set<ID> caseIds = new Set<ID>();
	if(trigger.isInsert || trigger.isUndelete){
		for(Case_Product__c cp : trigger.new){
			if(cp.Customer_ID__c != null){
				caseIds.add(cp.Case__c);
			}
		}
	}else if(trigger.isDelete){
		for(Case_Product__c cp : trigger.old){
			if(cp.Customer_ID__c != null){
				caseIds.add(cp.Case__c);
			}
		}		
	}else if(trigger.isUpdate){
		for(Case_Product__c cp : trigger.new){
			Case_Product__c old = trigger.oldMap.get(cp.id);
			if(cp.Customer_ID__c != old.Customer_ID__c){
				caseIds.add(cp.Case__c);
			}
		}		
	}
	if(!caseIds.isEmpty()){
		List<Case> cases = [select id, (select Customer_ID__c from Listings__r order by Customer_ID__c asc) from Case where id IN: caseIds];
		for(Case c : cases){
			String customerIds = '';
			for(Case_Product__c product : c.Listings__r){
				customerIds += product.Customer_ID__c + ', ';
			}
			if(customerIds.contains(',')){
				customerIds = customerIds.substring(0, customerIds.lastIndexOf(',')); //trim last comma;
			}
			//if(customerIds.length() > 255){
			//	customerIds = customerIds.substring(0,255);
			//}
			c.AF_Customer_ID__c = customerIds;
		}
		update cases;
	}
}